package atomic

import (
	"fmt"
	"sync/atomic"
	"time"
)

var i int64 = 0
var CAS_INT int64

func CasTest() {
	//go updateI()
	//fmtTest()
	CAS_INT = 0
	t1()
	start := time.Now()
	go func() {
		for {
			t2()
			x := start.Sub(time.Now())
			if x.Seconds() < -10 {
				fmt.Println(x)
				fmt.Println("?")
				//return
			}
		}
	}()
	go func() {
		for {
			t1()
		}
	}()
	for {

	}
}

func t1() {
	if atomic.CompareAndSwapInt64(&CAS_INT, 0, 1) {
		defer func() {
			atomic.CompareAndSwapInt64(&CAS_INT, 1, 0)
		}()
		fmt.Println("我要执行很久")
		time.Sleep(time.Second * 5)
	}
}
func t2() {
	if atomic.CompareAndSwapInt64(&CAS_INT, 0, 1) {
		defer func() {
			atomic.CompareAndSwapInt64(&CAS_INT, 1, 0)
		}()
		time.Sleep(time.Second * 1)
		fmt.Println("我执行不了")
	}
}

func fmtTest() {
	v := atomic.LoadInt64(&i)
	for {
		if atomic.CompareAndSwapInt64(&i, v, 0) {
			go gorun()
		} else {
			fmt.Println("被锁了")
		}
		//time.Sleep(time.Second*1)
	}
}

func gorun() {
	i = 1
	fmt.Println("查询AND修改")
	//time.Sleep(time.Second*2)
	i = 0
}

func updateI() {
	time.Sleep(time.Second * 10)
	i = 1
}
